/*
 * example5.c
 *
 * Created: 8/29/2013 1:05:36 AM
 *  Author: Tim
 */ 

#include "src/Epiphany.h"

PORT_t	*freqOutPort;
uint8_t freqOutPin;
uint8_t usbData;
int8_t pNumber = 0;

void freqOut(uint16_t freq, PORT_t *port, uint8_t pin);

void setup()
{
	//initialize system clock to 32MHz
	clockInit();
	
	//set ouptut frequency
	freqOut(1000,&PORTD,2);


	//global interrupt enable
	sei();
	
}

void loop()
{
	
}

void freqOut(uint16_t freq, PORT_t *port, uint8_t pin)
{
	uint32_t clockCycles = round(F_CPU/freq/2.0);
	uint8_t  division;
	
	freqOutPort = (PORT_t *)port;
	freqOutPin = pin;
	port->DIRSET = 1<<pin;
	
	if		(clockCycles > UINT16_MAX * 1024)
	{
		clockCycles = round(clockCycles/1024);
		division = TC_CLKSEL_DIV1024_gc;
	}
	else if (clockCycles > UINT16_MAX * 256)
	{
		clockCycles = round(clockCycles/256);
		division = TC_CLKSEL_DIV256_gc;
	}
	else if (clockCycles > UINT16_MAX * 64)
	{
		clockCycles = round(clockCycles/64);
		division = TC_CLKSEL_DIV64_gc;
	}
	else if (clockCycles > UINT16_MAX * 8)
	{
		clockCycles = round(clockCycles/8);
		division = TC_CLKSEL_DIV8_gc;
	}
	else if (clockCycles > UINT16_MAX * 4)
	{
		clockCycles = round(clockCycles/4);
		division = TC_CLKSEL_DIV4_gc;
	}
	else if (clockCycles > UINT16_MAX * 2)
	{
		clockCycles = round(clockCycles/2);
		division = TC_CLKSEL_DIV2_gc;
	}
	else
	{
		division = TC_CLKSEL_DIV1_gc;
	}
	
	TCC0.CTRLA		= division;

	TCC0.PER		= clockCycles;

	TCC0.CTRLA		= TC_WGMODE_SS_gc;

	TCC0.INTCTRLB	= TC_OVFINTLVL_MED_gc;

	PMIC.CTRL		= PMIC_MEDLVLEN_bm;
}

ISR(TCC0_OVF_vect)
{
	//toggle the pin
	freqOutPort->OUTTGL = 1<<freqOutPin;
}